package com.github.defense.plugin.gray.choose;

import com.github.defense.plugin.gray.instance.GrayInstance;
import com.github.defense.plugin.gray.instance.GrayInstanceList;
import com.github.defense.plugin.gray.instance.GrayInstanceSorter;
import com.github.defense.plugin.gray.server.ServerExplainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 默认灰度服务筛选器
 * @Author: lettger
 * @Date: 2021/6/9 12:52 下午
 */
@Slf4j
public class DefaultGrayServerChoose implements GrayServerChoose<Object> {

    private ServerExplainer serverExplainer;

    private GrayInstanceSorter instanceSorter;

    public DefaultGrayServerChoose(ServerExplainer serverExplainer,GrayInstanceSorter instanceSorter) {
        this.serverExplainer = serverExplainer;
        this.instanceSorter = instanceSorter;
    }

    @Override
    public Object choose(List<Object> list, ServerSelection<Object> selection) {
        // 1. 将服务列表转成可识别的灰度实例集合
        List<GrayInstance> grayInstances = serverExplainer.applys(list);
        // 2. 找到灰度服务和正常服务
        GrayInstanceList<Object> allInstances = instanceSorter.sorter(grayInstances);
        if(Objects.isNull(allInstances)){
            return selection.choose(list);
        }
        log.debug("grayInstances Num :{};normalInstances Num :{}",allInstances.getGrayInstance().size(),allInstances.getNormalInstance().size());
         // 3. 找到灰度服务
        if(!CollectionUtils.isEmpty(allInstances.getGrayInstance())){
            return selection.choose(allInstances.getGrayInstance());
        }
        // 4. 没有灰度服务 走正常服务
        if (!CollectionUtils.isEmpty(allInstances.getNormalInstance())) {
            return selection.choose(allInstances.getNormalInstance());
        }
        // 5. 都没有不管了则随机返回一个保证服务最小可用
        return selection.choose(list);
    }
}
